package com.example.demo.localcache.manager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.text.MessageFormat;
import java.util.List;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname CacheManagerTrigger
 * @description 定时、并按Order顺序刷新缓存
 * @date 2024/01/24 15:31
 * <p>
 * ******************************************************
 */
@Component
public class CacheManagerTrigger {

    /**
     * logger
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(CacheManagerTrigger.class);

    /**
     * 触发刷新缓存
     */
    @Scheduled(fixedRate = 1000 * 60, initialDelay = 1000 * 60)
    private static void refreshCache() {

        List<String> cacheNameList = getCacheList();

        LOGGER.info("start refresh instruction ,cacheNameList={}", cacheNameList);
        if (CollectionUtils.isEmpty(cacheNameList)) {
            LOGGER.warn("cache name list are empty");
            return;
        }

        long totalCacheSize = 0;
        for (String cacheName : cacheNameList) {
            CacheManagerRegistry.refreshCache(cacheName);
            totalCacheSize += CacheManagerRegistry.getCacheSize(cacheName);
        }
        LOGGER.info(MessageFormat.format("缓存刷新成功,缓存管理器:{0}个,总缓存条目数量:{1}条", cacheNameList.size(), totalCacheSize));
    }

    private static List<String> getCacheList() {
        return CacheManagerRegistry.getCacheNameList();
    }

}
